package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaOfficeSupplies;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.OaOfficeSuppliesService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.FileTools;
import com.dkm.orproject.utils.utils.IdToobtainUtils;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  @ClassName : OaOfficeSuppliesAction  //类名
 *  @Description : 办公用品  //描述
 *  @Author : 石智诚  //作者
 *  @Date: 2020-11-12 09:49  //时间
 */
@RestController
@RequestMapping("/OaOfficeSupplies")
public class OaOfficeSuppliesAction {
    /**
     * 办公用品
     */
    @Resource
    OaOfficeSuppliesService suppliesService;
    /**
     * 登录人
     **/
    OaPersonnel personnel;
    /**
     * 雪花算法
     */
    @Resource
    IdToobtainUtils utils;
    /**
     * 工具类
     */
    @Resource
    Tools tools;
    /**
     * 日志
     */
    OaLog log;
    /**
     * 回调map
     */
    Map<String, Object> map;
    /**
     * 行数
     */
    int row;
    @Resource
    FileTools fileTools;

    /**
     * 查询所有并进行分页
     *
     * @param officeSupplies 办公用品
     * @param page           页数
     * @param limit          显示的数量
     * @param request        请求
     * @return map
     */
    @UserLoginToken
    @GetMapping("/findAll")
    public Map<String, Object> findAll(OaOfficeSupplies officeSupplies, Integer page, Integer limit,
                                       String starteDate, String endDate, HttpServletRequest request) {
        rowMap(request);
        try {
            List<OaOfficeSupplies> all = suppliesService.findAll(officeSupplies, page, limit, starteDate, endDate);
            Long aLong = suppliesService.countAll(officeSupplies, starteDate, endDate);
            return Tools.maps(all, aLong);
        } catch (Exception e) {
            addErrorLog(request, "办公用品查询所有", e);
        }
        return null;
    }

    /**
     * 根据id查询
     *
     * @param id      办公用品id
     * @param request 请求
     * @return map
     */
    @UserLoginToken
    @GetMapping("findByIdOfficeSupplies/{id}")
    public Map<String, Object> findById(@PathVariable("id") Long id, HttpServletRequest request) {
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map, 0, log);
        }
        try {
            OaOfficeSupplies oaOfficeSupplies = suppliesService.selectById(id);
            map.put("data", oaOfficeSupplies);
        } catch (Exception e) {
            addErrorLog(request, "办公用品查询", e);
        }
        return map;
    }

    /**
     * 办公用品更新或者增加
     *
     * @param oaOfficeSupplies 办公用品
     * @param request          请求
     * @return 成功与否
     */
    @UserLoginToken
    @PostMapping("addorUpdateOfficeSupplies")
    public Map<String, Object> addOrUpdateOfficeSupplies(OaOfficeSupplies oaOfficeSupplies, HttpServletRequest request) {
        rowMap(request);
        if (ObjectUtils.isEmpty(oaOfficeSupplies)) {
            return tools.rowMap(map, 0, log);
        }
        try {
            if (oaOfficeSupplies.getPkOfficeSuppliesId() != null && oaOfficeSupplies.getPkOfficeSuppliesId() > 0) {
                // 创建人，创建时间，办公用品ID
                oaOfficeSupplies.setUpdatedBy(personnel.getPersonnelName());
                oaOfficeSupplies.setUpdatedTime(new Date());
                row = suppliesService.updateById(oaOfficeSupplies);
                log.setLogTitle("办公用品更新");
            } else {
                oaOfficeSupplies.setCreatedBy(personnel.getPersonnelName());
                oaOfficeSupplies.setCreatedTime(new Date());
                row = suppliesService.insert(oaOfficeSupplies);
                log.setLogTitle("办公用品增加");
            }
            log.setLogBody(JSON.toJSON(oaOfficeSupplies).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request, "办公用品增加或者更新", e);
        }
        return map;
    }

    /**
     * 根据id删除
     *
     * @param id      办公用品id
     * @param request 请求
     * @return map
     */
    @UserLoginToken
    @DeleteMapping("deleteOfficeSupplies/{id}")
    public Map<String, Object> deleteById(@PathVariable("id") Long id, HttpServletRequest request) {
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map, 0, log);
        }
        try {
            OaOfficeSupplies supplies = suppliesService.selectById(id);
            row = suppliesService.deleteById(id);
            log.setLogBody(JSON.toJSON(supplies).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            //收集错误信息
            addErrorLog(request, "办公用品删除", e);
        }
        return map;
    }

    /**
     * 办公用品批量删除
     *
     * @param ids     办公用品id
     * @param request 请求
     * @return map
     */
    @UserLoginToken
    @DeleteMapping("/officeDeleteAll")
    public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids, HttpServletRequest request) {
        rowMap(request);
        if (ObjectUtils.isEmpty(ids)) {
            tools.rowMap(map, 0, log);
        }
        try {
            List<Long> idss = Arrays.asList(ids);
            List<OaOfficeSupplies> all = suppliesService.findByAll(idss);
            row = suppliesService.deleteAll(idss);
            log.setLogBody(JSON.toJSONString(all).toString());
            log.setLogTitle("办公用品批量删除");
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request, "111", e);
        }
        return map;
    }

    /**
     * 用于图片上传的
     *
     * @param file 文件
     * @return 地址
     */
    @PostMapping("/saveFile")
    public Map<String, Object> saveFile(@RequestBody MultipartFile file) {
        Map<String, Object> map = new ConcurrentHashMap<>(16);
        try {
            map.put("file", fileTools.saveFiletwo("publicFile", file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 简化代码
     *
     * @param request 请求
     */
    private void addErrorLog(HttpServletRequest request, String title, Exception e) {
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        log = new OaLog();
        log.setLogType("0");
        log.setLogBody(e.getLocalizedMessage());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if (ObjectUtils.isEmpty(personnel)) {
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }

    private void rowMap(HttpServletRequest request) {
        //新建返回Map模型
        map = new HashMap<>(16);
        //获取登陆人信息
        personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log = new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

}
